#include "serialcontroller.h"

SerialController::SerialController(QObject *parent) :
    QObject(parent),
    mCurrentPort(nullptr),
    mProto(nullptr),
    mConnected(false),
    mListener(nullptr)
{

}

int SerialController::OpenSerial(QString port, QString baudRate, QString dataBits, QString stopBits, QString flow){
    GetSetting(baudRate,dataBits,stopBits,flow);
    mCurrentPort = new QSerialPort();
    if(nullptr == mCurrentPort){
        return NULLPOINTER;
    }
    mCurrentPort->setPortName(port);
    mCurrentPort->setBaudRate(mBaudrate);
    mCurrentPort->setDataBits(mDataBits);
    mCurrentPort->setStopBits(mStopBits);
    mCurrentPort->setFlowControl(mFlow);
    mCurrentPort->open(QIODevice::ReadWrite);
    if(!mCurrentPort->isOpen()){
        qDebug()<< mCurrentPort->errorString();
        return  -1;
    }
    connect(mCurrentPort, SIGNAL(readyRead()), SLOT(ReadyRead()));
    connect(mCurrentPort, SIGNAL(aboutToClose()),SLOT(AboutClose()));
    this->mConnected = true;
    return OK;
}

int SerialController::CloseSerial()
{
    if(this->mConnected){
        this->mCurrentPort->close();
    }
    return OK;
}

QList<QSerialPortInfo> SerialController::GetPorts()
{
    this->mPorts = QSerialPortInfo::availablePorts();
    return mPorts;
}

int SerialController::SetProto(QSerialProto * proto)
{
    this->mProto = proto;
    return OK;
}

int SerialController::SetListener(SerialController::SerialListener *p)
{
    mListener = p;
}

int SerialController::SendData(char *data, uint8_t len)
{
    if(mConnected){
        qDebug()<<data<<len;
        return mCurrentPort->write((char *)data,len);
    }
    return ERROR_SEND;
}

void SerialController::GetSetting(QString baudRate, QString dataBits, QString stopBits, QString flow)
{

    if (stopBits == "1") {
        mStopBits = QSerialPort::StopBits::OneStop;
    }
    if (stopBits == "1.5") {
        mStopBits = QSerialPort::StopBits::OneAndHalfStop;
    }
    if (stopBits == "2") {
        mStopBits = QSerialPort::StopBits::TwoStop;
    }
    if(flow == "none")
        mFlow = QSerialPort::FlowControl::NoFlowControl;
    if(flow == "software")
        mFlow = QSerialPort::FlowControl::SoftwareControl;
    if(flow == "hardware")
        mFlow = QSerialPort::FlowControl::HardwareControl;
    mBaudrate = baudRate.toUInt();
    mDataBits = (QSerialPort::DataBits)dataBits.toUInt();
    mParity = QSerialPort::Parity::NoParity;
}

void SerialController::ReadyRead()
{
    if (this->mCurrentPort->bytesAvailable() > 0) {
        auto data = mCurrentPort->readAll();
        if(nullptr != this->mProto){
            mProto->OnSerailData(data);
        }
        if(nullptr != this->mListener){
            mListener->OnDataRecv(data);
        }
    }
}

void SerialController::AboutClose() {

}
